using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Text;
using WebApplication1.Implement.DTO;
using WebApplication1.Implement.IServices;

namespace WebApplication1.Implement.Services
{
    /// <summary>
    /// AI服务实现类，支持多种AI提供商
    /// </summary>
    public class AIService : IAIService
    {
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _configuration;
        private readonly ILogger<AIService> _logger;
        private readonly string _provider;
        private readonly string _apiKey;
        private readonly string _modelId;
        private readonly string _baseUrl;

        public AIService(HttpClient httpClient, IConfiguration configuration, ILogger<AIService> logger)
        {
            _httpClient = httpClient;
            _configuration = configuration;
            _logger = logger;

            // 读取AI配置
            _provider = _configuration["AI:Provider"] ?? "openai";
            _apiKey = _configuration[$"AI:{_provider.ToUpper()}:ApiKey"] ?? "";
            _modelId = _configuration[$"AI:{_provider.ToUpper()}:ModelId"] ?? GetDefaultModel(_provider);
            _baseUrl = _configuration[$"AI:{_provider.ToUpper()}:BaseUrl"] ?? GetDefaultBaseUrl(_provider);

            _logger.LogInformation("AI服务初始化完成，提供商: {Provider}, 模型: {Model}", _provider, _modelId);
        }

        public async Task<string> GetAIResponseAsync(string message, List<ChatHistoryItem>? conversationHistory = null, string? systemPrompt = null)
        {
            try
            {
                if (string.IsNullOrEmpty(_apiKey) || _apiKey.Contains("your-") || _apiKey.Contains("api-key-here"))
                {
                    _logger.LogWarning("AI API密钥未配置，使用增强智能回退逻辑");
                    return GetEnhancedIntelligentResponse(message, conversationHistory, systemPrompt);
                }

                return _provider.ToLower() switch
                {
                    "openai" => await CallOpenAIAsync(message, conversationHistory, systemPrompt),
                    "azure" => await CallAzureOpenAIAsync(message, conversationHistory, systemPrompt),
                    "claude" => await CallClaudeAsync(message, conversationHistory, systemPrompt),
                    "gemini" => await CallGeminiAsync(message, conversationHistory, systemPrompt),
                    "qianwen" => await CallQianwenAsync(message, conversationHistory, systemPrompt),
                    "zhipu" => await CallZhipuAsync(message, conversationHistory, systemPrompt),
                    _ => throw new NotSupportedException($"不支持的AI提供商: {_provider}")
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "AI服务调用失败，使用增强回退逻辑");
                return GetEnhancedIntelligentResponse(message, conversationHistory, systemPrompt);
            }
        }

        public async Task<bool> IsAvailableAsync()
        {
            try
            {
                if (string.IsNullOrEmpty(_apiKey) || _apiKey.Contains("your-") || _apiKey.Contains("api-key-here"))
                {
                    return false;
                }

                // 发送简单的测试请求
                var testResponse = await GetAIResponseAsync("测试连接", null, "请简单回复'连接正常'");
                return !string.IsNullOrEmpty(testResponse);
            }
            catch
            {
                return false;
            }
        }

        public string GetModelName()
        {
            return $"{_provider}:{_modelId}";
        }

        #region OpenAI API调用

        private async Task<string> CallOpenAIAsync(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var messages = BuildMessageList(message, conversationHistory, systemPrompt);
            
            var requestBody = new
            {
                model = _modelId,
                messages = messages,
                max_tokens = 2000,
                temperature = 0.7,
                stream = false
            };

            return await SendHttpRequestAsync(_baseUrl + "/chat/completions", requestBody, "Bearer " + _apiKey);
        }

        #endregion

        #region Azure OpenAI API调用

        private async Task<string> CallAzureOpenAIAsync(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var messages = BuildMessageList(message, conversationHistory, systemPrompt);
            
            var requestBody = new
            {
                messages = messages,
                max_tokens = 2000,
                temperature = 0.7,
                stream = false
            };

            var headers = new Dictionary<string, string>
            {
                { "api-key", _apiKey }
            };

            return await SendHttpRequestAsync(_baseUrl, requestBody, null, headers);
        }

        #endregion

        #region Claude API调用

        private async Task<string> CallClaudeAsync(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var messages = BuildClaudeMessageList(message, conversationHistory);
            
            var requestBody = new
            {
                model = _modelId,
                max_tokens = 2000,
                temperature = 0.7,
                system = systemPrompt ?? GetDefaultSystemPrompt(),
                messages = messages
            };

            var headers = new Dictionary<string, string>
            {
                { "x-api-key", _apiKey },
                { "anthropic-version", "2023-06-01" }
            };

            return await SendHttpRequestAsync(_baseUrl + "/messages", requestBody, null, headers);
        }

        #endregion

        #region Gemini API调用

        private async Task<string> CallGeminiAsync(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var fullPrompt = BuildFullPrompt(message, conversationHistory, systemPrompt);
            
            var requestBody = new
            {
                contents = new[]
                {
                    new
                    {
                        parts = new[]
                        {
                            new { text = fullPrompt }
                        }
                    }
                },
                generationConfig = new
                {
                    temperature = 0.7,
                    maxOutputTokens = 2000
                }
            };

            var url = $"{_baseUrl}/models/{_modelId}:generateContent?key={_apiKey}";
            return await SendHttpRequestAsync(url, requestBody);
        }

        #endregion

        #region 千问API调用

        private async Task<string> CallQianwenAsync(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var messages = BuildMessageList(message, conversationHistory, systemPrompt);
            
            var requestBody = new
            {
                model = _modelId,
                input = new
                {
                    messages = messages
                },
                parameters = new
                {
                    max_tokens = 2000,
                    temperature = 0.7
                }
            };

            var headers = new Dictionary<string, string>
            {
                { "Authorization", "Bearer " + _apiKey }
            };

            return await SendHttpRequestAsync(_baseUrl, requestBody, null, headers);
        }

        #endregion

        #region 智谱API调用

        private async Task<string> CallZhipuAsync(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var messages = BuildMessageList(message, conversationHistory, systemPrompt);
            
            var requestBody = new
            {
                model = _modelId,
                messages = messages,
                max_tokens = 2000,
                temperature = 0.7,
                stream = false
            };

            var headers = new Dictionary<string, string>
            {
                { "Authorization", "Bearer " + _apiKey }
            };

            return await SendHttpRequestAsync(_baseUrl + "/chat/completions", requestBody, null, headers);
        }

        #endregion

        #region 辅助方法

        private async Task<string> SendHttpRequestAsync(string url, object requestBody, string? authHeader = null, Dictionary<string, string>? customHeaders = null)
        {
            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            _httpClient.DefaultRequestHeaders.Clear();
            
            if (!string.IsNullOrEmpty(authHeader))
            {
                _httpClient.DefaultRequestHeaders.Add("Authorization", authHeader);
            }

            if (customHeaders != null)
            {
                foreach (var header in customHeaders)
                {
                    _httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            var response = await _httpClient.PostAsync(url, content);
            var responseContent = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogError("AI API调用失败: {StatusCode}, {Content}", response.StatusCode, responseContent);
                throw new HttpRequestException($"AI API调用失败: {response.StatusCode}");
            }

            return ExtractResponseContent(responseContent, _provider);
        }

        private string ExtractResponseContent(string responseJson, string provider)
        {
            try
            {
                dynamic result = JsonConvert.DeserializeObject(responseJson);
                
                return provider.ToLower() switch
                {
                    "openai" or "azure" or "zhipu" => result?.choices?[0]?.message?.content?.ToString() ?? "",
                    "claude" => result?.content?[0]?.text?.ToString() ?? "",
                    "gemini" => result?.candidates?[0]?.content?.parts?[0]?.text?.ToString() ?? "",
                    "qianwen" => result?.output?.text?.ToString() ?? "",
                    _ => result?.ToString() ?? ""
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "解析AI响应失败: {Response}", responseJson);
                return "抱歉，我无法理解您的问题，请重新描述。";
            }
        }

        private List<object> BuildMessageList(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var messages = new List<object>();

            // 添加系统提示词
            if (!string.IsNullOrEmpty(systemPrompt))
            {
                messages.Add(new { role = "system", content = systemPrompt });
            }
            else
            {
                messages.Add(new { role = "system", content = GetDefaultSystemPrompt() });
            }

            // 添加对话历史
            if (conversationHistory != null && conversationHistory.Any())
            {
                foreach (var item in conversationHistory.TakeLast(10)) // 只保留最近10条
                {
                    messages.Add(new { role = item.Role, content = item.Content });
                }
            }

            // 添加当前消息
            messages.Add(new { role = "user", content = message });

            return messages;
        }

        private List<object> BuildClaudeMessageList(string message, List<ChatHistoryItem>? conversationHistory)
        {
            var messages = new List<object>();

            // Claude不需要系统消息在messages中，会单独处理
            if (conversationHistory != null && conversationHistory.Any())
            {
                foreach (var item in conversationHistory.TakeLast(10))
                {
                    if (item.Role != "system") // Claude系统消息单独处理
                    {
                        messages.Add(new { role = item.Role, content = item.Content });
                    }
                }
            }

            messages.Add(new { role = "user", content = message });
            return messages;
        }

        private string BuildFullPrompt(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var prompt = new StringBuilder();
            
            prompt.AppendLine(systemPrompt ?? GetDefaultSystemPrompt());
            prompt.AppendLine();

            if (conversationHistory != null && conversationHistory.Any())
            {
                foreach (var item in conversationHistory.TakeLast(10))
                {
                    var role = item.Role == "user" ? "用户" : "助手";
                    prompt.AppendLine($"{role}: {item.Content}");
                }
            }

            prompt.AppendLine($"用户: {message}");
            prompt.AppendLine("助手: ");

            return prompt.ToString();
        }

        private string GetDefaultSystemPrompt()
        {
            return @"你是一个专业的MES生产管理系统智能客服助手。你的职责是：

1. 帮助用户了解和使用MES生产管理系统的各项功能
2. 解答关于工单管理、工序流程、报工等相关问题
3. 提供系统操作指导和最佳实践建议
4. 协助解决用户在使用系统过程中遇到的问题

请注意：
- 始终使用中文回复
- 保持专业、友好的语调
- 如果不确定答案，请诚实说明并建议联系技术支持
- 优先提供具体、可操作的建议
- 关注生产制造领域的专业术语和流程
- 回答要简洁明了，重点突出";
        }

        private string GetDefaultModel(string provider)
        {
            return provider.ToLower() switch
            {
                "openai" => "gpt-3.5-turbo",
                "azure" => "gpt-35-turbo",
                "claude" => "claude-3-sonnet-20240229",
                "gemini" => "gemini-pro",
                "qianwen" => "qwen-turbo",
                "zhipu" => "glm-4",
                _ => "gpt-3.5-turbo"
            };
        }

        private string GetDefaultBaseUrl(string provider)
        {
            return provider.ToLower() switch
            {
                "openai" => "https://api.openai.com/v1",
                "azure" => "https://your-resource.openai.azure.com/openai/deployments/your-deployment/chat/completions?api-version=2023-12-01-preview",
                "claude" => "https://api.anthropic.com/v1",
                "gemini" => "https://generativelanguage.googleapis.com/v1beta",
                "qianwen" => "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
                "zhipu" => "https://open.bigmodel.cn/api/paas/v4",
                _ => "https://api.openai.com/v1"
            };
        }

        /// <summary>
        /// 增强的智能回复（支持上下文和系统提示词）
        /// </summary>
        private string GetEnhancedIntelligentResponse(string message, List<ChatHistoryItem>? conversationHistory, string? systemPrompt)
        {
            var context = BuildContextFromHistory(conversationHistory);
            var response = GetIntelligentFallbackResponse(message, context);
            
            // 添加上下文相关的回复
            if (!string.IsNullOrEmpty(context))
            {
                response = EnhanceResponseWithContext(response, context);
            }
            
            return response;
        }

        /// <summary>
        /// 构建上下文信息
        /// </summary>
        private string BuildContextFromHistory(List<ChatHistoryItem>? conversationHistory)
        {
            if (conversationHistory == null || !conversationHistory.Any())
                return string.Empty;

            var recentMessages = conversationHistory.TakeLast(4).ToList();
            var context = new StringBuilder();
            
            foreach (var item in recentMessages)
            {
                if (item.Role == "user")
                {
                    context.AppendLine($"用户问过: {item.Content}");
                }
            }
            
            return context.ToString();
        }

        /// <summary>
        /// 根据上下文增强回复
        /// </summary>
        private string EnhanceResponseWithContext(string baseResponse, string context)
        {
            if (context.Contains("工单") && !baseResponse.Contains("工单"))
            {
                return "根据您之前的问题，您对工单管理比较关心。" + baseResponse;
            }
            
            if (context.Contains("报工") && !baseResponse.Contains("报工"))
            {
                return "继续您之前关于报工的问题，" + baseResponse;
            }
            
            return baseResponse;
        }

        private string GetIntelligentFallbackResponse(string message, string context = "")
        {
            var lowerMessage = message.ToLower();

            // 基于关键词的智能回复
            if (lowerMessage.Contains("你好") || lowerMessage.Contains("您好") || lowerMessage.Contains("hello"))
            {
                return "您好！我是MES生产管理系统的智能客服助手。我可以帮助您解答工单管理、工序流程、生产报工等相关问题。请告诉我您需要什么帮助？";
            }

            if (lowerMessage.Contains("工单"))
            {
                return "关于工单管理，我可以帮您了解：\n• 工单创建和审核流程\n• 工单状态查询和跟踪\n• 工单修改和取消操作\n• 工单数据统计分析\n\n请告诉我您具体想了解工单的哪个方面？";
            }

            if (lowerMessage.Contains("工序") || lowerMessage.Contains("流程"))
            {
                return "关于工序流程管理，包括：\n• 工艺路线设计和配置\n• 工序标准时间设定\n• 质量检查点设置\n• 工序执行状态监控\n\n您想了解工序的具体哪个功能？";
            }

            if (lowerMessage.Contains("报工") || lowerMessage.Contains("生产"))
            {
                return "关于生产报工功能：\n• 实时生产数据录入\n• 产量和质量数据统计\n• 工时记录和效率分析\n• 异常情况处理流程\n\n请问您需要了解报工的哪个具体操作？";
            }

            // 智能分析用户意图
            return AnalyzeUserIntentAndRespond(message, context);
        }

        /// <summary>
        /// 分析用户意图并智能回复
        /// </summary>
        private string AnalyzeUserIntentAndRespond(string message, string context)
        {
            var lowerMessage = message.ToLower();
            
            // 复杂问题分析
            if (lowerMessage.Contains("为什么") || lowerMessage.Contains("原因"))
            {
                return AnalyzeProblemCause(message);
            }
            
            if (lowerMessage.Contains("怎么办") || lowerMessage.Contains("如何解决"))
            {
                return ProvideSolution(message);
            }
            
            if (lowerMessage.Contains("比较") || lowerMessage.Contains("区别"))
            {
                return ProvideComparison(message);
            }
            
            if (lowerMessage.Contains("步骤") || lowerMessage.Contains("流程"))
            {
                return ProvideStepByStep(message);
            }
            
            // 默认智能回复
            return "我是MES系统的智能助手！我可以帮您解答工单管理、工序流程、生产报工等相关问题。请告诉我您的具体问题，我会尽力为您提供帮助！";
        }
        
        private string AnalyzeProblemCause(string message)
        {
            if (message.Contains("登录"))
                return "登录问题分析：\n• 用户名或密码错误\n• 账户被锁定或禁用\n• 网络连接问题\n• 浏览器缓存问题\n\n建议按顺序检查这些可能原因。";
            
            if (message.Contains("慢"))
                return "系统响应慢的原因：\n• 网络带宽不足\n• 服务器负载过高\n• 数据库查询复杂\n• 浏览器资源占用过多\n\n可以尝试关闭不必要的标签页或清理缓存。";
            
            return "我正在分析您描述的问题原因。请提供更具体的错误信息或现象描述，这样我可以给出更准确的分析。";
        }
        
        private string ProvideSolution(string message)
        {
            if (message.Contains("工单"))
                return "工单问题解决方案：\n1. 检查工单状态是否正确\n2. 确认所需权限是否具备\n3. 刷新页面重新加载数据\n4. 联系管理员检查系统设置\n\n如果问题依然存在，请提供具体的错误信息。";
            
            return "解决方案建议：\n• 先尝试刷新页面\n• 检查网络连接\n• 清理浏览器缓存\n• 联系技术支持\n\n请告诉我具体遇到了什么问题，我可以提供更针对性的解决方案。";
        }
        
        private string ProvideComparison(string message)
        {
            return "比较分析：\n我可以帮您比较MES系统中的不同功能、流程或操作方式。请告诉我您想比较的具体内容，比如：\n• 不同的工单类型\n• 各种报工方式\n• 系统模块功能\n\n这样我可以给出更详细的对比分析。";
        }
        
        private string ProvideStepByStep(string message)
        {
            if (message.Contains("工单"))
                return "工单操作步骤：\n\n创建工单：\n1. 登录MES系统\n2. 进入工单管理模块\n3. 点击新建工单\n4. 填写产品信息和数量\n5. 选择工艺路线\n6. 保存并提交审核\n\n需要其他操作的详细步骤吗？";
            
            return "操作步骤指导：\n请告诉我您想了解哪个具体功能的操作步骤，比如：\n• 工单创建流程\n• 生产报工操作\n• 质量检验流程\n• 库存管理操作\n\n我会为您提供详细的分步指导。";
        }

        #endregion
    }
}
